from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from .models import Area
from .serializers import AreasSerializer, SubSerializer


class ArealListView(APIView):
    """查询所有省"""

    def get(self, request):
        # 1.获取指定的查询集
        qs = Area.objects.filter(parent=None)
        print(qs)
        # 2.创建序列化器进行序列化
        serializer = AreasSerializer(qs, many=True)
        # 3.响应
        return Response(serializer.data)


class AreaDetailView(APIView):
    """查询单一省或市"""

    def get(self, request, pk):
        # 1.根据ps查询出指定的省或市
        try:
            area = Area.objects.get(id=pk)
        except Area.DoesNotExist:
            return Response({'message': '无效的pk'}, status=status.HTTP_400_BAD_REQUEST)
        # 2.创建序列化器进行序列化
        serializer = SubSerializer(area)
        # 3.响应
        return Response(serializer.data)


class AreaModelViewSet(CacheResponseMixin, ReadOnlyModelViewSet):

    def get_queryset(self):
        if self.action == 'list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()

    def get_serializer_class(self):
        if self.action == 'list':
            return AreasSerializer
        elif self.action == 'retrieve':
            return SubSerializer

